local noscript = require "noscript"
local webview = require "webview"
local modes = require "modes"
local settings = require "settings"
local formfiller = require "formfiller"
local lousy = require "lousy"

last_uri = ""

settings.window.home_page = "https://html.duckduckgo.com/html"

noscript.enable_scripts = false
noscript.enable_plugins = false

local engines = settings.window.search_engines
engines.default = "https://html.duckduckgo.com/html/?q=%s"
engines.searx = "https://searx.be/search?q=%s"
engines.amuse = "https://amuse.apiote.xyz/items/?q=%s"
engines.wiki = function (arg)
	local l, s = arg:match("^(%a%a):%s*(.+)")
	if l then
		return "https://" .. l .. ".wikipedia.org/wiki/Special:Search?search=" .. s
	else
		return "https://en.wikipedia.org/wiki/Special:Search?search=" .. arg
	end
end,

modes.add_binds("normal", {{
		",R",
		"Force reload into http.",
		function (w)
			uri = w.view.uri
			uri = uri:gsub("https://", "http://")
			last_uri = uri
			w:navigate(uri)
			msg.info("forcing " .. uri)
		end
}})

modes.add_binds("normal", {{
	"<Control-Shift-c>", "Copy selected text.", function ()
		luakit.selection.clipboard = luakit.selection.primary
	end
}})

modes.add_cmds({{":qute", function (w)
		uri = w.view.uri
		luakit.spawn(string.format("%s %q", "qutebrowser", uri))
	end
}})

webview.add_signal("init", function(view)
	view:add_signal("navigation-request", function (v, uri)
	if string.match(string.lower(uri), "^magnet:") then
		luakit.spawn(string.format("%s %q", "transmission-gtk", uri))
		return false
	end
	if string.match(string.lower(uri), "^gemini://") then
		_, stdout, _ = luakit.spawn_sync(string.format("/home/adam/.local/bin/fun gmi %q", uri))
		view:load_string(stdout, uri)
		return false
	end
	if not string.match(uri, "duckduckgo.com") then
		if string.match(uri, "pkg.go.dev") then
			v.uri = uri:gsub("pkg.go.dev", "godocs.io")
			return false
		end
		if string.match(uri, "www.reddit.com") then
			v.uri = uri:gsub("www.reddit.com", "libredd.it")
			return false
		end
		if string.match(uri, "twitter.com") then
			v.uri = uri:gsub("twitter.com", "nitter.unixfox.eu")
			return false
		end
		if string.match(uri, "youtube.com") then
			v.uri = uri:gsub("www.youtube.com", "invidious.fdn.fr")
			v.uri = v.uri:gsub("youtube.com", "invidious.fdn.fr")
			return false
		end
	end
	if string.match(uri, "localhost") or string.match(uri, "deepthought") then
		last_uri = uri
		return true
	end
	if uri == last_uri then
		msg.info("backing down from forcing https")
		return true
	end
	last_uri = uri
	if string.match(uri, "http!://") then
			uri = uri:gsub("http!://", "http://")
			v.uri = uri
			msg.info("forcing http")
			return false
	end
	if string.match(uri, "^http://") then
			v.uri = uri:gsub("http://", "https://")
			msg.info("forcing https")
			return false
		end
	end)
end)

formfiller.extend({
		nextpass = function(label, user) return io.popen("/home/adam/.local/bin/eeze -Gf password -l" .. label .. " -u" .. user):read() end
})
